//
//  HSScrollView.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 15/12/28.
//  Copyright © 2015年 haisheng huang. All rights reserved.
//

import UIKit

@objc
public enum HSScrollViewType: Int {
    case contentView
    case infiniteScroll
    case autoInfiniteScroll
    case photoBrowse
}

@available(iOS 7.0, *)
open class HSScrollView: UIScrollView, UIScrollViewDelegate {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    //private var pageControl: HSPageControl? = nil
    fileprivate var scrollType: HSScrollViewType? = .contentView
    var autoScrollInterval: Double = 2.5
    var backupViews: NSArray? = nil
    var autoTimer: Timer? = nil
    var autoTimerInterval: TimeInterval? = 0.0
    
    deinit {
        self.stopAutoChangeTimer()
    }
    
    public convenience init(type: HSScrollViewType, frame: CGRect, views: NSArray) {
        
        self.init()
        self.frame = frame
        
        //loasSubViews
        self.setScrollType(type, views: views)
        
    }

    func setScrollType(_ type: HSScrollViewType, views: NSArray) {
        
        //Base property
        self.setScrollBaseProperty()
        
        if type == .contentView {
            self.loadContentView(views)
        } else if type == .infiniteScroll {
            self.loadInfiniteScroll(views)
        } else if type == .autoInfiniteScroll {
            self.loadAutoInfiniteScroll(self.autoScrollInterval, views: views)
        } else if type == .photoBrowse {
            self.loadPhotoBrowse(views)
        }
        
    }
    
    fileprivate func setScrollBaseProperty() {
        
        self.showsHorizontalScrollIndicator = false
        self.showsVerticalScrollIndicator = false
        self.isPagingEnabled = true
        super.delegate = self
    }
    
    func loadContentView(_ views: NSArray?) {
        
        guard views != nil else { return }
        
        guard views?.count != 0 else { return }
        
        for i in 0..<views!.count {
            
            if views![i] is UIViewController {
                let templeView = views![i] as! UIViewController
                self.addSubview(templeView.view)
                
            } else if (views![i] as AnyObject).isKind(of: UIView.self) {
                
                let templeView = views![i]
                var frame: CGRect = (templeView as AnyObject).frame
                frame.origin.x = self.frame.size.width * CGFloat(i)
                frame.size = self.frame.size
                (templeView as! UIView).frame = frame
                self.addSubview(templeView as! UIView)
            }
        }
        
        let contentSize = CGSize(width: self.frame.width * CGFloat((views?.count)!), height: self.frame.height)
        self.contentSize = contentSize
        
        self.backupViews = views
    }
    
    func loadInfiniteScroll(_ views: NSArray?) {
        
        guard views != nil else { return }
        
        guard views?.count != 0 else { return }
        
        print("constraints:\(self.constraints),count:\(self.constraints.count)");
        
        for i in 0..<views!.count {
            
//            if views![i].isKindOfClass(UIView) {
//                let templeView = views![i]
//                var frame: CGRect = templeView.frame
//                frame.origin.x = self.frame.size.width * CGFloat(i)
//                frame.size = self.frame.size
//                (templeView as! UIView).frame = frame
//                self.addSubview(templeView as! UIView)
//            }
            let templeView = self.createCustomItemView(views![i] as AnyObject?)
            var templeFrame = templeView.frame
            templeFrame.origin.x = CGFloat(i + 1) * self.frame.width
            templeFrame.size = self.frame.size
            templeView.frame = templeFrame
            self.addSubview(templeView)
            
        }
        
        let firstView: UIView = self.createCustomItemView(views?.lastObject as AnyObject?)
        var firstFrame = firstView.frame
        firstFrame.origin.x = 0
        firstFrame.size = self.frame.size
        firstView.frame = firstFrame
        self.addSubview(firstView)
        
        let lastView: UIView = self.createCustomItemView(views?.firstObject as AnyObject?)
        var lastFrame = lastView.frame
        lastFrame.origin.x = CGFloat(views!.count + 1) * self.frame.width
        lastFrame.size = self.frame.size
        lastView.frame = lastFrame
        self.addSubview(lastView)
        
        let contentSize = CGSize(width: self.frame.width * CGFloat((views?.count)! + 2), height: self.frame.height)
        self.contentSize = contentSize
        self.contentOffset.x = self.frame.width
        
        self.backupViews = views
        
        //print("subViews: \(self.subviews), \(self.subviews.count)")
    }
    
    func loadAutoInfiniteScroll(_ interval: Double, views: NSArray?) {
        
        guard views != nil else { return }
        
        guard views?.count != 0 else { return }
        
        self.loadInfiniteScroll(views)
        
        self.startAutoChangeTimer(2.5)
        
//        let pageControl: HSPageControl = HSPageControl(type: HSPageControlType.rightBottom, superView: self, numberOfPages: views!.count, currentPage: 0)
//        pageControl.currentPageIndicatorTintColor = UIColor.blueColor()
//        pageControl.pageIndicatorTintColor = UIColor.grayColor()
//        pageControl.layer.borderColor = UIColor.blackColor().CGColor
//        pageControl.layer.borderWidth = 0.5
//        
//        self.pageControl = pageControl
        
//        print("scroll view: \(self.pageControl)")
    }
    
    func loadPhotoBrowse(_ views: NSArray?) {
        
        guard views != nil else { return }
        
        guard views?.count != 0 else { return }
        
        for i in 0..<views!.count {
            
            if (views![i] as AnyObject).isKind(of: UIView.self) {
                let templeView = views![i]
                var frame: CGRect = (templeView as AnyObject).frame
                frame.origin.x = self.frame.size.width * CGFloat(i)
                frame.size = self.frame.size
                (templeView as! UIView).frame = frame
                self.addSubview(templeView as! UIView)
            }
        }
        
        let contentSize = CGSize(width: self.frame.width * CGFloat((views?.count)!), height: self.frame.height)
        self.contentSize = contentSize
        
        self.backupViews = views
        
    }
    
    func startAutoChangeTimer(_ interval: TimeInterval) {
        
        guard interval > 0.0 else {return}
        
        self.autoTimerInterval = interval
        
        if self.autoTimer != nil {
            self.autoTimer?.invalidate()
            self.autoTimer = nil
        }
        
        self.autoTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(HSScrollView.movoToTargetPosition), userInfo: nil, repeats: true)
    }
    
    func stopAutoChangeTimer() {
        
        guard self.autoTimer != nil else {return}
        
        self.autoTimer?.invalidate()
        self.autoTimer = nil
        
    }
    
    func pauseAutoChangeTimer() {
        
        self.autoTimer?.fireDate = Date.distantFuture
        
    }
    
    func resumeAutoChangeTimer() {
        self.autoTimer?.fireDate = Date(timeIntervalSinceNow: 2.0)
    }
    
    func movoToTargetPosition() {
        
        var currentPoint: CGPoint = self.contentOffset
        
        if currentPoint.x == self.frame.width * CGFloat(backupViews!.count + 1) {
        
            currentPoint.x = self.frame.width
            self.setContentOffset(currentPoint, animated: false)
        
        }
        
        let nextPoint = CGPoint(x: currentPoint.x + self.frame.size.width, y: currentPoint.y)
        
        self.setContentOffset(nextPoint, animated: true)
        
        let currentPage: Int = Int(floor((self.contentOffset.x - self.frame.width/CGFloat(self.backupViews!.count + 2))/self.frame.width)) + 1
        
        if currentPage == 0 {
            
            var tempFrame = self.frame
            tempFrame.origin.x = self.frame.width * CGFloat((self.backupViews?.count)!)
            self.scrollRectToVisible(tempFrame, animated: false)
            
//            if self.pageControl != nil {
//                self.pageControl?.currentPage = (self.backupViews?.count)! - 1
//            }
//            
        } else if currentPage == (self.backupViews?.count)! + 1 {
            
            var tempFrame = self.frame
            tempFrame.origin.x = self.frame.width
            
            self.scrollRectToVisible(tempFrame, animated: false)
            
//            if self.pageControl != nil {
//                self.pageControl?.currentPage = 0
//            }
            
        } else {
            
//            if currentPage == self.backupViews?.count {
//                self.pageControl?.currentPage = 0
//            } else {
//                self.pageControl?.currentPage = currentPage
//            }
        }
        
        print("currentPage: \(currentPage)")
    }
    
    //UIScrollViewDelegate
    
    open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
       
        let currentPage: Int = Int(floor((self.contentOffset.x - self.frame.width/CGFloat(self.backupViews!.count + 2))/self.frame.width)) + 1
        
        if currentPage == 0 {
            
            var tempFrame = self.frame
            tempFrame.origin.x = self.frame.width * CGFloat((self.backupViews?.count)!)
            self.scrollRectToVisible(tempFrame, animated: false)
            
//            if self.pageControl != nil {
//                self.pageControl?.currentPage = (self.backupViews?.count)! - 1
//            }
            
        } else if currentPage == (self.backupViews?.count)! + 1 {
            
            var tempFrame = self.frame
            tempFrame.origin.x = self.frame.width
            
            self.scrollRectToVisible(tempFrame, animated: false)
            
//            if self.pageControl != nil {
//                self.pageControl?.currentPage = 0
//            }
            
        } else {
            
//            if self.pageControl != nil {
//                self.pageControl?.currentPage = currentPage - 1
//            }
        }
        
        self .resumeAutoChangeTimer()
    }
    
    open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        if self.autoTimer != nil {
            self.pauseAutoChangeTimer()
        }
    }
    
    func createCustomItemView(_ viewData: AnyObject?) -> UIView {
        let view: UIView = UIView()
        view.frame.origin = CGPoint.zero
        view.backgroundColor = viewData as? UIColor
        return view
    }
    
}
